<template>
    <div class="main">
        <el-card :body-style="{ padding: '0px' }">
            <div class="card-view">
                <div class="boxLeft">
                    <div class="cardLeft">
                        <div class="pic">
                            <img src="@/assets/image/ron.png" alt="" />
                        </div>
                        <p>欢迎</p>
                        <p>智学商城-后台管理系统</p>
                    </div>
                </div>
                <div class="boxRight">
                    <div class="cardRight">
                        <h4>登录</h4>
                        <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules">
                            <el-form-item prop="username">
                                <el-input v-model="ruleForm.username" type="text" :prefix-icon="User" autocomplete="off"
                                    class="input" />
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input v-model="ruleForm.password" type="password" :prefix-icon="Lock"
                                    autocomplete="off" class="input" />
                            </el-form-item>
                            <div class="login-btn">
                                <el-button type="primary" @click="handleLogin(ruleFormRef)">登录</el-button>
                            </div>
                        </el-form>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'//引入ref和reactive函数,实现数据响应式
import { Lock, User } from '@element-plus/icons-vue';//图标 
import { useRoute, useRouter } from 'vue-router'//路由跳转
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'//提示信息
import cookie from 'js-cookie'//引入处理cookies的Api
import { post } from "@/utils/http"; //封装的axios请求方式
import { useUserStore } from "@/stores/admin/index"; //引入pinia中的状态容器
import { debounce } from "@/utils/DebounceThrottle";

const route = useRoute()
const router = useRouter()//实例化路由函数
const store = useUserStore()//实例化pinia中的容器函数
const ruleFormRef = ref<FormInstance>() //获取节点
const ruleForm = reactive({
    username: '',
    password: '',
})
// 表单非空验证
const validateUser = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入账户'))
    }
    callback()
}
const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    }
    callback()
}
//验证规则
const rules = reactive({
    username: [{ validator: validateUser, trigger: 'blur' }],
    password: [{ validator: validatePass, trigger: 'blur' }]
})

let handleLogin = (formEl: FormInstance | undefined) => { };
handleLogin = debounce(submitForm, 600)

// 登录
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            post({ _gp: "admin", _mt: "login", ...ruleForm }).then((res) => {
                console.log(res);
                Object.assign(store.loginInfo, ruleForm);//将账号密码存储到pinia中
                let { data: token, errno, errmsg } = res;
                if (200 == errno) { //判断状态
                    ElMessage.success('登录成功！')
                    let date = new Date();//获取当前时间
                    date.setTime(date.getTime() + 1000 * 60 * 30);//设置当前时间延长半个小时
                    cookie.set("token", token, { expires: date })//token写入到cookie,设置过期时间
                    return Promise.resolve(token)//返回一个成功的Promise对象再次进行请求
                } else {
                    return Promise.reject(errmsg)//返回一个失败的Promise对象再次进行请求
                }
            }).then((res) => {
                // 请求个人信息数据
                post({ _gp: 'admin', _mt: 'info' }).then((res) => {
                    console.log(res);
                    let { data, errno, errmsg } = res
                    if (200 == errno) {
                        store.setUser(data); //调用pinia中的setUser事件，将数据数据传入piia状态容器
                        let back = route.query.back //从路由数据中拿到上次登录进入页面的路由
                        if (back) {
                            router.replace(<string>back)//登录时跳转到上次登录的页面
                            return
                        }
                        router.replace('/')
                    } else {
                        return Promise.reject(errmsg)
                    }
                })
            }).catch((err) => {
                console.log(err);
                ElMessage.error(err)
            })
        } else {
            return false
        }
    })
}

</script>

<style lang="less" scoped>
.main {
    width: 100%;
    height: 100vh;
    background: url(../assets/image/bg.jpg) 0 0 no-repeat;
    background-size: 100% 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    overflow: hidden;

    .el-card {
        border: 0;
        display: inline-block;
    }

    .card-view {
        width: 45vw;
        height: 65vh;
        display: flex;
    }

    .boxLeft {
        background-color: #005de9;
        width: 40%;
        height: 100%;
        color: white;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;

        .cardLeft {
            width: 100%;
            height: 50%;

            .pic {
                width: 50%;
                height: 60%;
                border-radius: 50%;
                background-color: #005de9;
                box-shadow: 4px -4px 30px #fff;
                overflow: hidden;
                border: 1px solid #ccc;
                margin: auto;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            p {
                text-align: center;
            }
        }
    }

    .boxRight {
        width: 60%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: white;

        .cardRight {
            width: 80%;

            .input {
                height: 40px;
            }

            h4 {
                margin-top: 0;
                text-align: center;
            }

        }
    }

    .login-btn {
        display: flex;
        justify-content: center;

        button {
            width: 40%;
            height: 45px;
        }
    }
}
</style>